package cc.dullsky.util;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class ToutiaoUtil {
	private static final String FAVORITES_URL = "http://toutiao.com/api/favorites";

	/**
	 * 获取头条网我的收藏列表
	 * 
	 * @return List<Map<String, String>>
	 */
	public static List<Map<String, String>> getFavorites() {
		List<Map<String, String>> list = new ArrayList<>();
		Map<String, String> sessionMap = new HashMap<>();
		sessionMap.put("sessionid", "2f8cae655c1a9841cf29764422c4d96a");
		try {
			Response response = Jsoup.connect(FAVORITES_URL).timeout(20000).cookies(sessionMap).ignoreContentType(true).execute();
			String jsonString = response.body();
			JSONArray array = JSONObject.parseObject(jsonString).getJSONArray("data");
			for (int i = 0; i < array.size(); i++) {
				Map<String, String> map = new HashMap<>();
				JSONObject object = array.getJSONObject(i);
				String article_url = object.getString("article_url");
				URL url = new URL(article_url);
				map.put("domain", url.getHost());
				map.put("title", object.getString("title"));
				map.put("url", article_url);
				map.put("refer", object.getString("group_id"));
				list.add(map);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 头条-根据网址获取文章内容
	 * 
	 * @param url
	 *            文章地址
	 * @return String 文章内容
	 */
	public static String getArticleByToutiao(String url) {
		try {
			Document document = Jsoup.connect(url).timeout(20000).get();
			Elements elements = document.getElementsByClass("article-content");
			if (elements.size() > 0) {
				Element element = elements.get(0);
				return element.html();
			}
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}
